import { getDataType, getMetaData } from './service';
import type { Reducer, Effect } from 'umi';

interface DataSetType {
  label: string;
  value: string;
  tasks: {
    label: string;
    value: string;
    annotFormats: {
      label: string;
      value: string;
    }[]
  }[]
}

const formatData = (data: DataSetType[]) => {
  return data?.map(item => ({
    ...item,
    children: item.tasks?.map(i => ({
      ...i,
      children: i.annotFormats?.map(j => ({
        ...j,
      })),
      annotFormats: undefined,
    })),
    tasks: undefined,
  }))
};

export type DataType = {
  label: string;
  value: string;
  children?: DataType[];
}

export type StateType = {
  dataTypes: DataType[];
  annotStatus: DataType[];
  datasetStatus: DataType[];
  sourceType: DataType[];
}

type DataSetModelType = {
  namespace: string;
  state: StateType;
  effects: {
    getDataType: Effect;
    getMetaData: Effect;
  };
  reducers: {
    setState: Reducer<StateType>;
  };
};

const Modal: DataSetModelType = {
  namespace: 'dataSet',

  state: {
    dataTypes: [],       // 数据类型、数据任务及标注格式
    annotStatus: [],     // 标注状态
    datasetStatus: [],   // 数据集状态
    sourceType: [],      // 数据来源
  },

  effects: {
    *getDataType(_, { call, put }) {
      const res = yield call(getDataType);
      if (res.code === 0) {
        yield put({
          type: 'setState',
          payload: {
            dataTypes: formatData(res.data),
          }
        })
      }
    },
    *getMetaData(_, { call, put }) {
      const res = yield call(getMetaData);
      if (res.code === 0) {
        yield put({
          type: 'setState',
          payload: {
            annotStatus: res.data.annotStatus,
            sourceType: res.data.sourceType,
            datasetStatus: res.data.datasetStatus,
          }
        })
      }
    },
  },

  reducers: {
    setState(state, { payload }) {
      return {
        ...state,
        ...payload,
      }
    },
  }
}

export default Modal;